package server.net;

import java.io.IOException;
import java.nio.channels.*;

public class PlayerChannel {

	private PlayerBuffers playerBuffers;
	private SocketChannel socketChannel;

	public PlayerChannel(SocketChannel socketChannel) {
		this.socketChannel = socketChannel;
		this.playerBuffers = new PlayerBuffers();
	}

	public void disconnect() {
		try {
			socketChannel.close();
			System.out.println("Disconnected.");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public final void handleIncomingData() {
		try {
			if (socketChannel.read(playerBuffers.getInBuffer()) == -1) {
				disconnect();
				return;
			}
			playerBuffers.getInBuffer().flip();
			while (playerBuffers.getInBuffer().hasRemaining()) {
				System.out.println(playerBuffers.getInBuffer().get());
			}
			playerBuffers.getInBuffer().clear();
		} catch (Exception ex) {
			ex.printStackTrace();
			disconnect();
		}
	}

	public void sendBuffer() {
		playerBuffers.getOutBuffer().flip();
		try {
			socketChannel.write(playerBuffers.getOutBuffer());
		} catch (IOException ex) {
			ex.printStackTrace();
			disconnect();
		}
	}

	public SocketChannel getSocketChannel() {
		return socketChannel;
	}
	
	public PlayerBuffers getBuffers() {
		return playerBuffers;		
	}

}
